// server.js
const express = require('express')
const cors = require('cors')
const fs = require('fs')
const path = require('path')
const { Document, Packer, Paragraph } = require('docx')
const axios = require('axios') // 用于下载保存的文档

const app = express()
app.use(express.json())
app.use(cors());

const PORT = 3000
const serverUrl = `http://180.76.177.100:${PORT}`

// 🧩 1️⃣ 创建新 Word 文件
app.get('/api/create-doc', async (req, res) => {
  const doc = new Document({
    sections: [
      {
        children: [new Paragraph('')],
      },
    ],
  })

  const buffer = await Packer.toBuffer(doc)
  const filePath = path.join(__dirname, 'files', 'blank.docx')
  fs.writeFileSync(filePath, buffer)

  // 返回新文档的访问 URL
  res.json({
    code: 0,
    data: {
      url: `${serverUrl}/blank.docx`,
    },
  })
})

// 🧩 2️⃣ OnlyOffice 保存回调接口
app.post('/api/save', async (req, res) => {
  const body = req.body
  console.log('📩 收到 OnlyOffice 回调:', JSON.stringify(body, null, 2))

  try {
    // 只处理 status=2 的情况（文档保存完成）
    if (body.status === 2 && body.url) {
      const fileUrl = body.url
      const savePath = path.join(__dirname, 'files', 'new_saved.docx')

      const response = await axios.get(fileUrl, { responseType: 'arraybuffer' })
      fs.writeFileSync(savePath, response.data)
      console.log('✅ 文件已保存到:', savePath)
    }

    // 返回状态给 OnlyOffice
    res.json({ error: 0 })
  } catch (err) {
    console.error('❌ 保存出错:', err)
    res.json({ error: 1 })
  }
})

// 🧩 3️⃣ 静态资源目录（存放文档）
app.use(express.static(path.join(__dirname, 'files')))

app.listen(PORT, () => {
  console.log(`✅ Server running at http://localhost:${PORT}`)
})
